package paiement;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class Request {

	private String data;
	private String url;
	private String response="";
	
	public Request(String url, String data, String type){
		this.setUrl(url);
		this.setData(data);
		
		if(type.toLowerCase().equals("post"))
			this.processPost();
		
		if(type.toLowerCase().equals("get"))
			this.processGet();
	}
	
	public void processPost(){
		try {
		    // Construct data
		    String data = this.getData();
		    		
		    // Send data
		    URL url = new URL(this.getUrl());
		    URLConnection conn = url.openConnection();
		    conn.setDoOutput(true);
		    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
		    wr.write(data);
		    wr.flush();
	
		    // Get the response
		    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		    String line;
		    while ((line = rd.readLine()) != null) {
		    	response += line;
		    }
		    wr.close();
		    rd.close();
		} catch (Exception e) {
		}
		this.setResponse(response);
	}
	
	public void processGet(){
		
		String data = (!this.getData().trim().equals(""))?"?"+this.getData():"";
		try {
		    
			URL url = new URL(this.getUrl()+data);
		    
		    BufferedReader reader = null;
		    reader = new BufferedReader(new InputStreamReader(url.openStream()));
		    
		   	// Get the response
		    String line;
		    while ((line = reader.readLine()) != null) {
		        response += line;
		    }
		    reader.close();
		    
		} catch (Exception e) {
		}
		this.setResponse(response);
	}
	public String getData() {
		return data;
	}
	public void setData(String data) {
		this.data = data;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getResponse() {
		return response;
	}
	public void setResponse(String response) {
		this.response = response;
	}
}
